//
//  ClassifyContentViewController.swift
//  clreader
//
//  Created by colin on 2019/3/8.
//  Copyright © 2019 colin. All rights reserved.
//

import UIKit
import MJRefresh

class ClassifyContentViewController: CLBaseViewController {

    private lazy var infoTableView = UITableView(frame: CGRect.zero, style: .plain)
    private var infoData = [JSONObject]()
    private var page = Router.defaultPage
    private var taskHandle:URLSessionTask?
    private var cat_id:Int?
    
    convenience init(cat_id:Int?) {
        self.init()
        self.cat_id = cat_id
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        
        self.view.addSubview(self.infoTableView)
        self.infoTableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        self.infoTableView.do {
            $0.backgroundColor = UIColor.white
            $0.separatorStyle = .none
            $0.sectionHeaderHeight = 0
            $0.sectionFooterHeight = 0
            $0.estimatedRowHeight = 0
            $0.register(Cell.self, forCellReuseIdentifier: Cell.reuseId)
            $0.dataSource = self
            $0.delegate = self
            $0.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
                self?.refresh()
            })
            $0.mj_header?.beginRefreshing()
        }
    }
    
}

extension ClassifyContentViewController {
    
    private func refresh() {
        
        self.page = Router.defaultPage
        self.taskHandle?.cancel()
        self.infoTableView.mj_footer = nil
        self.taskHandle =
            Router.goods_list(cat_id: self.cat_id, type: nil,book_type: nil, pageNum: self.page, pageSize: Router.defaultPageSize).request { [weak self] (response:RequestResponse<JSONObject>) in
                
                self?.taskHandle = nil
                self?.infoTableView.mj_header.endRefreshing()
                
                if case .success(let successData,_) = response {
                    if let sources = successData?["rows"] as? [JSONObject] {
                        self?.page += 1
                        self?.infoData = sources
                        if sources.count >= Router.defaultPageSize {
                            self?.infoTableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
                                self?.loadMore()
                            })
                        }
                    } else {
                        self?.infoData = []
                    }
                    
                    self?.infoTableView.reloadData()
                }
                
                if case .failure(_,let message) = response {
                    self?.hud.showText(message)
                }
        }
    }
    
    private func loadMore() {
        
        if self.taskHandle != nil {
            return
        }
        
        self.taskHandle =
            Router.goods_list(cat_id: self.cat_id, type: nil,book_type: nil, pageNum: self.page, pageSize: Router.defaultPageSize).request { [weak self] (response:RequestResponse<JSONObject>) in
                
                self?.taskHandle = nil
                
                if case .success(let successData,_) = response {
                    if let sources = successData?["rows"] as? [JSONObject] {
                        
                        self?.page += 1
                        self?.infoData += sources
                        
                        if sources.count >= Router.defaultPageSize {
                            self?.infoTableView.mj_footer?.endRefreshing()
                        } else {
                            self?.infoTableView.mj_footer?.endRefreshingWithNoMoreData()
                        }
                        
                    } else {
                        self?.infoData = []
                        self?.infoTableView.mj_footer?.endRefreshingWithNoMoreData()
                    }
                    
                    self?.infoTableView.reloadData()
                }
                
                if case .failure(_,let message) = response {
                    self?.infoTableView.mj_footer?.endRefreshing()
                    self?.hud.showText(message)
                }
        }
    }
}

extension ClassifyContentViewController : UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.infoData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: Cell.reuseId) as! Cell
        cell.refresh(data: self.infoData[indexPath.row])
        return cell
    }
}

extension ClassifyContentViewController : UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return BookCell.height
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let itemData = self.infoData[indexPath.row]
        if let sourceType = SourceType(type: itemData["type"] as? Int),
            let goods_id = itemData["goods_id"] as? Int {
            if sourceType == .电子书 {
                let controller = EBookDetailViewController(goods_id: goods_id)
                self.show(controller, sender: nil)
            } else {
                let controller = SourceDetailViewController(sourceType: sourceType, goods_id: goods_id)
                self.show(controller, sender: nil)
            }
        }

    }
}

extension ClassifyContentViewController {
    
    class Cell: UITableViewCell {
        
        static let height:CGFloat = 100.0
        static let reuseId = "Cell"
        
        private lazy var imageViewInfo = UIImageView()
        private lazy var imageViewTypeTag = UIImageView()
        private lazy var labelName = UILabel()
        private lazy var labelBuyed = UILabel()
        private lazy var labelPrice = UILabel()
        
        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
            self.selectionStyle = .none
            
            let content = CLTouchableView().then {
                
                // 图片
                self.imageViewInfo.do {
                    $0.layer.masksToBounds = true
                    $0.layer.cornerRadius = 3.0
                }
                $0.addSubview(self.imageViewInfo)
                self.imageViewInfo.snp.makeConstraints({ (make) in
                    make.size.equalTo(CGSize(width: 90.0, height: 70.0))
                    make.left.equalToSuperview().offset(15.0)
                    make.centerY.equalToSuperview()
                })
                
                // 阴影背景
                let imageViewInfoShadow = UIView().then {
                    $0.backgroundColor = UIColor.black
                    $0.layer.cornerRadius = 3.0
                    $0.layer.shadowColor = UIColor.black.cgColor
                    $0.layer.shadowOffset = CGSize(width:2.0,height:4.0)
                    $0.layer.shadowOpacity = 0.3 //阴影
                }
                $0.insertSubview(imageViewInfoShadow, belowSubview: self.imageViewInfo)
                imageViewInfoShadow.snp.makeConstraints({ (make) in
                    make.edges.equalTo(self.imageViewInfo)
                })
                
                $0.addSubview(self.imageViewTypeTag)
                self.imageViewTypeTag.snp.makeConstraints({ (make) in
                    make.left.equalTo(self.imageViewInfo.snp.left).offset(-5.0)
                    make.bottom.equalTo(self.imageViewInfo.snp.bottom).offset(-5.0)
                    make.size.equalTo(CGSize(width: 56.0, height: 19.0))
                })
                
                // 名称
                self.labelName.do {
                    $0.numberOfLines = 2
                    $0.textColor = UIColor(hex: "343434")
                    $0.font = UIFont.systemFont(ofSize: 15.0, weight: .light)
                }
                $0.addSubview(self.labelName)
                self.labelName.snp.makeConstraints({ (make) in
                    make.left.equalTo(self.imageViewInfo.snp.right).offset(15.0)
                    make.right.equalToSuperview().offset(-15.0)
                    make.top.equalTo(self.imageViewInfo.snp.top).offset(3.0)
                })
            
                // 已购人数
                self.labelBuyed.do {
                    $0.textColor = UIColor(hex: "828282")
                    $0.font = UIFont.systemFont(ofSize: 11.0, weight: .light)
                }
                $0.addSubview(self.labelBuyed)
                self.labelBuyed.snp.makeConstraints({ (make) in
                    make.left.equalTo(self.imageViewInfo.snp.right).offset(15.0)
                    make.bottom.equalTo(self.imageViewInfo.snp.bottom).offset(-10.0)
                })
                
                // 价格
                self.labelPrice.do {
                    $0.textColor = UIColor(hex: "828282")
                    $0.font = UIFont.systemFont(ofSize: 12.0, weight: .light)
                }
                $0.addSubview(self.labelPrice)
                self.labelPrice.snp.makeConstraints({ (make) in
                    make.right.equalToSuperview().offset(-15.0)
                    make.bottom.equalTo(self.imageViewInfo.snp.bottom).offset(-10.0)
                })
                
            }
            self.contentView.addSubview(content)
            content.snp.makeConstraints { (make) in
                make.edges.equalToSuperview()
            }
            
        }
        
        func refresh(data:JSONObject?) {
            
            self.labelName.text = data?["title"] as? String
            
            // 已购数量
            if let trade_count = data?["trade_count"] as? Int {
                self.labelBuyed.text = "\(trade_count)人已购"
            } else {
                self.labelBuyed.text = ""
            }
            
            // 价格
            let price = data?["price"] as? Double
            self.labelPrice.attributedText = price?.priceAttr
            
            // 图片
            if let cover_url = data?["cover_url"] as? String,!cover_url.isEmpty,
                let baseUrl = URL(string: Router.baseUrl) {
                let imageUrl = baseUrl.appendingPathComponent(cover_url)
                self.imageViewInfo.kf.setImage(with: imageUrl)
            } else {
                self.imageViewInfo.image = nil
            }
            
            // 类型图片
            if let type = SourceType(type: data?["type"] as? Int),!type.tagName.isEmpty,
                let tagImage = UIImage(named: type.tagName) {
                self.imageViewTypeTag.image = tagImage
                
                self.imageViewTypeTag.isHidden = false
            } else {
                self.imageViewTypeTag.isHidden = true
            }
            
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    
}
